# !/usr/bin/env python
# -*- coding: UTF-8 -*-
# date: 12/21/11 12:48 PM
# Filename: handlers.py

#
# Copyright 2011 Youku
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

import os
import tornado.web
from util import log
from constants import RESP_CODE


### global variables ###
_log = log.getLogger()
_sep = os.linesep


class BaseHandler(tornado.web.RequestHandler):
    @property
    def db(self):
        _log.info('class:BaseHandler method:db()')
        return self.application.db


    def isdigit(self, value):
        if value is None:
            return False
        return value.isdigit()


    def writeAndFinish(self, content):
        if content:
            self.write(content)
            self.finish()

    def writeToDataFile(self, filepath, *fields):
        data_file = open(filepath, 'a')
        line = ' '.join(['{%s}' % i for i in xrange(len(fields))]).format(*fields)
        # TODO optimize file I/O operations , eg: writeLines() etc..
        data_file.write(line + _sep)
        data_file.close()


    def get(self, *args, **kwargs):
        _log.info('class:BaseHandler method:get()')

        self.set_header('Content-Type', 'text/plain')
        self.pid = self.get_argument('pid', None)
        self.guid = self.get_argument('guid', None)
        self.ver = self.get_argument('ver', None)
        self.network = self.get_argument('network', None)
        self.operator = self.get_argument('operator', None)

        if not self.pid:
            self.writeAndFinish(RESP_CODE.resp_code_invalid_pid)
        elif not self.guid:
            self.writeAndFinish(RESP_CODE.resp_code_invalid_guid)
        elif not self.ver:
            self.writeAndFinish(RESP_CODE.resp_code_invalid_ver)
        elif not self.network:
            self.writeAndFinish(RESP_CODE.resp_code_invalid_network)
        elif not self.operator:
            self.writeAndFinish(RESP_CODE.resp_code_invalid_operator)

        if self._finished:
            return None

        ### TODO : verify PID ###
        pid_object = None

        ### TODO : get pid from cache ###
        pid_from_cache = None

        if pid_from_cache:
            pid_object = pid_from_cache
        else:
            pid_object = self.db.get('select * from s_partner where pid = "%s" limit 1' % (self.pid))

        if not pid_object:
            self.writeAndFinish(RESP_CODE.resp_code_invalid_pid)

